package com.oop.example.gui;

import com.oop.example.data.HibernateUtil;
import com.oop.example.data.EntryPOJO;
import com.oop.example.processing.OnLoadMerger;
import com.oop.example.processing.ProcessingFactory;
import com.oop.example.processing.Reader;
import com.oop.example.work.bel.HtmlReader;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import javax.swing.DefaultComboBoxModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author -
 */
public class DBLoader extends javax.swing.JDialog {

    private boolean stop = false;

    public DBLoader(Window parent) {
        super(parent, ModalityType.APPLICATION_MODAL);
        initComponents();
        jButtonRun.addActionListener(new HandleActionListener());
        jButtonCancel.addActionListener(new CancelActionListener());
        jTextFieldDBFile.setText(HibernateUtil.getProperty(HibernateUtil.url));
        try {
            File htmlDir = new File("html");
            if (htmlDir.exists() && htmlDir.isDirectory() && htmlDir.listFiles().length > 0) {
                String[] sorted = htmlDir.list();
                Arrays.sort(sorted);
                jComboBoxSource.setModel(new DefaultComboBoxModel(sorted));
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextFieldDBFile = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButtonRun = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButtonCancel = new javax.swing.JButton();
        jLabelEncoding = new javax.swing.JLabel();
        jComboBoxEncoding = new javax.swing.JComboBox();
        jComboBoxSource = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Файл БД");

        jTextFieldDBFile.setEditable(false);

        jLabel2.setText("Исходный файл");

        jButtonRun.setText("Загрузка");

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        jTextPane1.setEditable(false);
        jScrollPane1.setViewportView(jTextPane1);

        jButtonCancel.setText("Прервать");

        jLabelEncoding.setText("Кодировка");

        jComboBoxEncoding.setEditable(true);
        jComboBoxEncoding.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "windows-1251", "UTF-8" }));

        jComboBoxSource.setEditable(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButtonCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRun))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabelEncoding))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldDBFile)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jComboBoxEncoding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jComboBoxSource, 0, 375, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldDBFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBoxSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelEncoding)
                    .addComponent(jComboBoxEncoding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonRun)
                    .addComponent(jButtonCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonRun;
    private javax.swing.JComboBox jComboBoxEncoding;
    private javax.swing.JComboBox jComboBoxSource;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelEncoding;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldDBFile;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

    private class CancelActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            stop = true;
        }
    }

    private class HandleActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            stop = false;
            new Thread((new Runnable() {
                @Override
                public void run() {
                    Session session = null;
                    try {
                        jTextPane1.setText("Начинаем загрузку ...");
                        String fileName = jComboBoxSource.getSelectedItem().toString();
                        File file = new File(fileName);
                        if (!file.exists()) {
                            file = new File("html", fileName);
                            if (!file.exists()) {
                                jTextPane1.setText("Исходный файл не найден");
                                return;
                            }
                        }
                        Reader reader = new ProcessingFactory().getReader();
                        reader.setEncoding(jComboBoxEncoding.getSelectedItem().toString());
                        String[] read = reader.read(file);
                        jProgressBar1.setMaximum(read.length);
                        int lineNum = 1;
                        Transaction transaction = null;
                        session = HibernateUtil.getSessionFactory().openSession();
                        //
                        transaction = session.beginTransaction();
                        jTextPane1.setText("Очистка БД...");
                        Query createQuery = session.createQuery("delete from EntryPOJO");
                        createQuery.executeUpdate();
                        //
                        ProcessingFactory factory = new ProcessingFactory();
                        OnLoadMerger merger = null;
                        if (merger == null) {
                            merger = factory.getOnLoadMerger();
                            merger.setFirst("");
                        }
                        boolean first = true;
                        for (String strLine : read) {
                            if (stop) {
                                jTextPane1.setText("Загрузка прервана");
                                break;
                            }

                            if (!merger.merge(strLine) && !first) {
                                EntryPOJO entry = new EntryPOJO();
                                entry.setID(lineNum);
                                entry.setContent(merger.getResult());
                                entry.setStatus(EStatus.NEW.getId());
                                entry.setComment("");
                                session.save(entry);
                                merger.setFirst(strLine);
                            }

                            jProgressBar1.setValue(lineNum);
                            lineNum++;
                            if (lineNum % 1000 == 0 || read.length == (lineNum + 1)) {
                                System.out.println("inserted rows " + lineNum);
                            }
                            jTextPane1.setText("Обработано " + lineNum + " строк");
                            first = false;
                        }
                        EntryPOJO entry = new EntryPOJO();
                        entry.setID(lineNum);
                        entry.setContent(merger.getResult());
                        entry.setStatus(EStatus.NEW.getId());
                        entry.setComment("");
                        session.save(entry);
                        jTextPane1.setText("Завершение ...");
                        transaction.commit();
                        jTextPane1.setText("Загрузка завершена успешно");
                    } catch (Exception ex) {
                        ex.printStackTrace(System.out);
                        jTextPane1.setText("Ошибка загружки =( : " + ex.getLocalizedMessage());
                    } finally {
                        if (session != null && session.isOpen()) {
                            session.close();
                        }
                    }

                }
            })).start();
        }
    }
}
